package com.huike.aspectj;

import com.huike.common.annotation.PreAuthorize;
import com.huike.common.exception.CustomException;
import com.huike.web.service.PermissionService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 权限认证切面类
 */
@Slf4j
@Aspect
@Component
public class PermissionAuthAspect {

    @Autowired
    PermissionService permissionService;

    /**
     * 拦截controller层带PreAuthorize注解的方法
     *
     * @param joinPoint
     */
    @Before("@annotation(com.huike.common.annotation.PreAuthorize) && execution(* com.huike.controller..*.*(..))")
    public void perAuth(JoinPoint joinPoint) {
        //1. 获取注解的权限标识符
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        String preStr = method.getAnnotation(PreAuthorize.class).value();

        //2. 判断用户是否包含权限
        if (!permissionService.hasPermission(preStr)) {
            //抛异常
            throw new CustomException("用户权限不足！");
        }
    }

}
